<template>
  <el-tree-select
    v-model="selectedClass"
    :data="classList"
    :placeholder="placeholder"
    :props="defaultProps"
    check-strictly
    @change="handleChange"
  />
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import * as MaterialApi from '@/api/material/course'
import { handleTree } from '@/utils/tree'

// 定义组件属性
const props = defineProps({
  // 分类类型
  type: {
    type: Number,
    required: true
  },
  // 占位符文本
  placeholder: {
    type: String,
    default: '请选择分类'
  },
  // 默认选中的值
  modelValue: {
    type: [String, Number],
    default: ''
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'change'])

// 数据相关
const selectedClass = ref(props.modelValue)
const classList = ref<any[]>([])

// 树形配置
const defaultProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}

// 获取分类数据
const getClassList = async () => {
  const res = await MaterialApi.getMaterialClassList(props.type)
  classList.value = handleTree(res)
}

// 选择变化处理
const handleChange = (val: string | number) => {
  emit('update:modelValue', val)
  emit('change', val)
}

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  (newVal) => {
    selectedClass.value = newVal
  }
)

// 组件挂载时获取数据
onMounted(() => {
  getClassList()
})

// 暴露方法给父组件
defineExpose({
  getClassList
})
</script>
